package tum0r.utils;

import tum0r.enums.HashMode;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 工程: FileSync<br>
 * 包: tum0r.utils<br>
 * 创建者: tum0r<br>
 * 创建时间: 2021/6/17 09:39<br>
 * <br>
 */
public class Hash {
    public static String encrypt(byte[] data, HashMode mode) {
        StringBuilder result = new StringBuilder();
        if (data != null && data.length != 0 && mode != null) {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance(mode.value);
                byte[] encryptionData = messageDigest.digest(data);
                String hex;
                for (byte d : encryptionData) {
                    hex = Integer.toHexString(d & 0xff);
                    if (hex.length() == 1) {
                        result.append("0");
                    }
                    result.append(hex);
                }
            } catch (NoSuchAlgorithmException ignored) {
            }
        }
        return result.toString();
    }

    public static String encrypt(String text, HashMode mode) {
        if (StringExtension.isNotNullOrEmpty(text) && mode != null) {
            return encrypt(text.getBytes(StandardCharsets.UTF_8), mode);
        }
        return "";
    }
}
